#ParallelPlatform Project - A web platform to distribute and share knowledge
#Copyright (C) 2011  Daniel Guerrero Martinez & Sergio Rodriguez Lumley
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from models import Page
from form import PageForm
from django.conf import settings
from xml.dom import minidom
from django.utils.translation import get_language
from django.utils.translation import ugettext as _

def listLinkChildren(father, level, options, raiz=''):
    childs = father.children.all().order_by('siblingPosition')
    list = ""
    if len(childs) > 0:
        list = "<ul>"
        for child in childs:
            if (not child.valid and 'disable' in options and options['disable']) or child.valid:
                list += '<li><a href="/'+child.uuid+'/" '
                if not child.valid:
                    list+='class="disabled"'
                list += '>'+child.getRevisionValid().title
                if child.getRevisionValid().lang != get_language():
                    list += ' <span class="'+child.getRevisionValid().lang+'">('+child.getRevisionValid().lang+')</span>'
                list +='</a>'
                if not child.valid:
                    list+=' ('+_("Disabled")+') '+'<a class="normallink" href="/'+child.uuid+'/enable/">'+_("Click here to enable")+'</a>'
                if level > 1 and child.children.exists() :
                    list += listLinkChildren(child, level-1, options, raiz+child.uuid+'/')
                list += '</li>'
        list += "</ul>"
    return list

def tree(father):
    list = ''
    list += '<li><a href="'+father.getPath()+'">'+father.getRevisionValid().title+'</a>'
    for lang in settings.LANGUAGES:
        revisions = father.revision.filter(lang=lang[0]).all()
        if len(revisions) > 0:
            list += '<span class="langbox"><span class="'+lang[0]+'">['+lang[0]+']</span>'
            for rev in revisions:
                list +=' <a href="'+father.getPath()+'?version='+str(rev.version)+'&lang='+lang[0]+'" title="'+_("Open this version to revise it")+'">v'+str(rev.version)+'</a>'
            list += '</span>'
    
    list +='<span class="cpanel">'
    # Page enabled
    list +='<div class="cbox"><span class="cbox valid'
    if father.valid:
        list += ' checked'
    list += '" title="'+_("Enabled or not")+'"></span></div><input type="checkbox" name="'+father.uuid+'" value="enable"'
    if father.valid:
        list +='checked '
    list += '>'
    
    # Page editable
    list +='<div class="cbox"><span class="cbox editable'
    if father.editable:
        list += ' checked' 
    list += '" title="'+_("Editable or not")+'"></span></div><input type="checkbox" name="'+father.uuid+'" value="editable"'
    if father.editable:
        list +='checked '
    list += '>'
    
    # Page can have children
    list +='<div class="cbox"><span class="cbox newchildren'
    if father.newChildren:
        list +=' checked'
    list += '" title="'+_("Can add pages or not")+'"></span></div><input type="checkbox" name="'+father.uuid+'" value="newChildren"'
    if father.newChildren:
        list +='checked '
    list += '>'
    
    list +='</span>'
    
    list +='</li>'
    if father.children.exists():
        list+='<ul>'
        for son in father.children.all():
            list+=tree(son)
        list += "</ul>"
    return list

def getAction(page,user):
    
    dic = {}
    
    if not user.is_anonymous():
    
        if (page.newChildren or page in user.owner.all() or user.has_perm("permissions_wiki.can_admin_page")) and user.has_perm("permissions_wiki.can_create_page"):
            dic['newChildren'] = True
        
        if (page.editable or page in user.owner.all() or user.has_perm("permissions_wiki.can_admin_page")):
            if user.has_perm("permissions_wiki.can_edit_page"):
                dic['edit'] = True
            if not page.valid and user.has_perm("permissions_wiki.can_enable_page"):
                dic['enable'] = True
            if page.valid and user.has_perm("permissions_wiki.can_disable_page"):
                dic['disable'] = True
            if user.has_perm("permissions_wiki.can_erase_page"):
                dic['erase'] = True
            if user.has_perm('permissions_wiki.can_admin_page'):
                dic['commit'] = True
    return dic
    
def getPage(id,full=False):
    
    try:
        page = Page.objects.get(uuid=id)
        list = []
        correct = True
        father = page
        
        while father is not None:
            if not father.valid and not full:
                return [False,None,None]
            list.insert(0, [father.getPath() ,father.getRevisionValid()])
            father = father.father

    except Page.DoesNotExist:
        return [False,None,None]
        
    return [correct,page,list]

def getRoot():
    try:
        root = Page.objects.get(father=None)
    except Page.DoesNotExist:
        root = Page(type=0)
        root.save()
        root = Page.objects.get(father=None)
    
    return root
        
class PageTemplate():
        
    def __init__(self, type ,file):
        xmlparser = minidom.parse(settings.WIKI_TEMPLATE_DIR+"/"+file)
                        
        urlImage = xmlparser.getElementsByTagName('image')[0].firstChild.data
        for l in xmlparser.getElementsByTagName('lang'):
            if l.getAttribute('id') == get_language():
                self.type = type
                self.title = l.getElementsByTagName('title')[0].firstChild.data
                self.description = l.getElementsByTagName('description')[0].firstChild.data
                self.urlImage = urlImage
                
                # Extract the content in a string form
                filee = open(settings.WIKI_TEMPLATE_DIR+"/"+file)
                text = filee.read().decode('utf8')
                filee.close()
                text = text[text.find('<lang id="'+get_language()+'">'):] # Get the text from the selected language to the end 
                text = text[text.find("<content>")+9:text.find("</content>")] # Get the first occurrence of <content> (which will be in the specified language) and remove "<content>" from it
                
                cleantext = ""
                for txt in text.splitlines():
                    cleantext += txt.strip()
                
                self.form = PageForm(initial={
                                      'type' : type,
                                      'title' : l.getElementsByTagName('contentTitle')[0].firstChild.data, 
                                      'content' : cleantext})#l.getElementsByTagName('content')[0].firstChild.data } )
        
        
def json_response(data):
    import json
    from django.http import HttpResponse
    return HttpResponse(json.dumps(data, sort_keys=True),
                        content_type='application/json; charset=UTF-8')
    
    




        